package com.ruoyi.auth.controller;

import com.ruoyi.common.core.context.SecurityContextHolder;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.system.api.domain.ChangePassword;
import com.ruoyi.auth.form.LoginBody;
import com.ruoyi.system.api.domain.RegisterInfo;
import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.auth.AuthUtil;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteEmailService;
import com.ruoyi.system.api.RemoteSmsService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * token 控制
 *
 * @author ruoyi
 */
@RestController
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private RemoteEmailService remoteEmailService;
    @Autowired
    private RemoteSmsService remoteSmsService;
    @Autowired
    private RemoteUserService remoteUserService;
    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form)
    {
        // 用户登录
//        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        LoginUser userInfo = sysLoginService.loginMixed(form);
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            if(StringUtils.isEmpty(ServletUtils.getHeader(request, SecurityConstants.ENTERPRISE_CODE))){
                SecurityContextHolder.setEnterpriseCode("-");
            }else {
                SecurityContextHolder.setEnterpriseCode(ServletUtils.getHeader(request, SecurityConstants.ENTERPRISE_CODE));
            }
            if(StringUtils.isEmpty(ServletUtils.getHeader(request, SecurityConstants.APPLICATION_CODE))){
                SecurityContextHolder.setApplicationCode(SecurityConstants.IGNORE_APPLICATION_CODE);
            }else {
                SecurityContextHolder.setApplicationCode(ServletUtils.getHeader(request, SecurityConstants.APPLICATION_CODE));
            }
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterInfo registeinfo)
    {
        // 用户注册
        return sysLoginService.registerTenantInfo(registeinfo);
    }
    @PostMapping("/sms/sendSmsVerifyCode/{mobile}")
    public R<?> sendSmsVerifyCode(@PathVariable("mobile") String mobile)
    {
        return remoteSmsService.sendSmsVerifyCode(mobile);
    }
    /**
     * 验证码短信验证码
     *
     * @param  mobile 手机号
     * @param  code   验证码
     * @return 结果
     */
    @PostMapping("/sms/verifyCode/{mobile}/{code}")
    public R<Boolean> smsVerifyCode(@PathVariable("mobile") String mobile,@PathVariable("code") String code){
        return remoteSmsService.verifyCode(mobile,code);
    }
    /**
     * 发送验证码
     *
     * @param mail 邮箱
     * @return 结果
     */
    @PostMapping("/mail/sendSmsVerifyCode/{mail}")
    public R<Boolean> sendMailVerifyCode(@PathVariable("mail") String mail){
        return remoteEmailService.sendVerifyCode(mail);
    }

    /**
     * 验证码邮件验证码
     *
     * @param mail 邮箱
     * @param code 验证码
     * @return 结果
     */
    @PostMapping("/mail/verifyCode/{mail}/{code}")
    public R<Boolean> mailVerifyCode(@PathVariable("mail") String mail,@PathVariable("code") String code){
        return remoteEmailService.verifyCode(mail,code);
    }
    /**
     * 检查手机号唯一性
     * @param phone
     * @return
     */
    @PostMapping("/checkPhoneUnique/{phone}")
    public R<Boolean> checkPhoneUnique(@PathVariable("phone") String phone){
        return remoteUserService.checkPhoneUnique(phone, SecurityConstants.INNER);
    }

    /**
     * 修改密码
     * @param changePassword
     * @return
     */
    @PostMapping("changePasword")
    public R<Boolean> changePasword(@RequestBody ChangePassword changePassword)
    {
        // 用户登录
        return remoteUserService.changePasword(changePassword,SecurityConstants.INNER);
    }
}
